﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using com.tiyma.common;
using com.tiyma.model;
using System.Data.SqlClient;

namespace com.tiyma.data
{
    public class UserDao
    {

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="i_user_id"></param>
        /// <returns></returns>
        public UserInfo GetUserInfoByUserId(long i_user_id)
        {
            string t_str_sql = string.Format("select * from tbUser where userId={0}", i_user_id);

            UserInfo t_user = null;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        t_user = new UserInfo();
                        t_user.UserId = Convert.ToInt32(reader["userId"].ToString());
                        t_user.UserName = reader["userName"].ToString();
                        t_user.Password = reader["password"].ToString();
                        t_user.Phone = reader["phone"].ToString();
                        t_user.Email = reader["email"].ToString();
                        t_user.BookCount = reader["bookCount"] == DBNull.Value ? 0 : Convert.ToInt32(reader["bookCount"].ToString());
                        t_user.BirthDay = reader["birthday"] == DBNull.Value ? DateTime.MaxValue : Convert.ToDateTime(reader["birthday"].ToString());
                        t_user.NickName = reader["nickName"].ToString();
                        break;

                    }

                    return t_user;

                }
            }
            catch (Exception ex)
            {
                throw new DataException("获取用户登陆信息失败", ex);
            }
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="i_user"></param>
        /// <returns></returns>
        public int UpdateUser(UserInfo i_user)
        {
            string t_str_sql = string.Format("update tbUser {0}phone='{1}',email='{2}',nickName='{3}',birthday='{4}' where userId='{5}'",
                string.IsNullOrEmpty( i_user.Password)?"":string.Format("set password='{0}',",i_user.Password), i_user.Phone, i_user.Email, i_user.NickName, i_user.BirthDay, i_user.UserId);

            try
            {
                return DBHelper.ExecuteSql(t_str_sql);
            }
            catch (Exception ex)
            {
                throw new DataException("更新用户信息失败", ex);
            }
        }

        /// <summary>
        /// 用户登陆，获取登陆信息
        /// </summary>
        /// <param name="i_user_name"></param>
        /// <param name="i_password"></param>
        /// <returns></returns>
        public UserInfo GetUserInfo(string i_user_name, string i_password)
        {
            string t_str_sql = string.Format("select * from tbUser where userName='{0}' and password='{1}'", i_user_name, i_password);

            UserInfo t_user= null;

            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        t_user = new UserInfo();
                        t_user.UserId = Convert.ToInt32(reader["userId"].ToString());
                        t_user.UserName = reader["userName"].ToString();
                        t_user.Password = reader["password"].ToString();
                        t_user.Phone = reader["phone"].ToString();
                        t_user.Email = reader["email"].ToString();
                        t_user.BookCount = reader["bookCount"] == DBNull.Value ? 0 : Convert.ToInt32(reader["bookCount"].ToString());
                        t_user.BirthDay = reader["birthday"] == DBNull.Value ? DateTime.MaxValue : Convert.ToDateTime(reader["birthday"].ToString());
                        t_user.NickName = reader["nickName"].ToString();
                        break;
                     
                    }

                    return t_user;

                }
            }
            catch (Exception ex)
            {
                throw new DataException("获取用户登陆信息失败", ex);
            }
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="i_user_name"></param>
        /// <param name="i_password"></param>
        /// <param name="i_email"></param>
        /// <returns></returns>
        public Consts.ResultType RegisterUser(string i_user_name, string i_password, string i_email,out int o_user_id)
        {
            string t_str_sql = "select count(userId) totalCount from tbuser where userName='{0}'";

            int t_ret=0;
            int t_exists = 0;
            o_user_id = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {
                        
                        if (!int.TryParse(reader["totalCount"].ToString(), out t_exists))
                            t_exists = 0;
                        break;
                    }

                    if (t_exists > 0)
                        return Consts.ResultType.Exists;

                    
                }

                t_str_sql = string.Format("insert into tbuser(userName,password,email)values('{0}','{1}','{2}')", i_user_name, i_password, i_email);

                t_ret = DBHelper.ExecuteSql(t_str_sql);

                if (t_ret > 0)
                {
                    t_str_sql = string.Format("select userId from tbUser where userName='{0}'", i_user_name);
                    using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                    {
                        while (reader.Read())
                        {

                            if (!int.TryParse(reader["userId"].ToString(), out o_user_id))
                                o_user_id = 0;
                            break;
                        }

                    }
                    return Consts.ResultType.Successed;
                }

                return Consts.ResultType.Faild;
            }
            catch (Exception ex)
            {
                throw new DataException("注册用户失败" + ex.ToString());
            }

           

        }

        /// <summary>
        /// 检查用户是否存在
        /// </summary>
        /// <param name="i_user_name"></param>
        /// <returns></returns>
        public Consts.ResultType CheckUserExists(string i_user_name)
        {
            string t_str_sql =string.Format( "select count(userId) totalCount from tbuser where userName='{0}'",i_user_name);

            int t_exists = 0;
            try
            {
                using (SqlDataReader reader = DBHelper.ExecuteReader(t_str_sql))
                {
                    while (reader.Read())
                    {

                        if (!int.TryParse(reader["totalCount"].ToString(), out t_exists))
                            t_exists = 0;
                        break;
                    }

                    if (t_exists > 0)
                        return Consts.ResultType.Exists;


                }

                return Consts.ResultType.Successed;
            }
            catch (Exception ex)
            {
                throw new DataException("注册用户失败" + ex.ToString());
            }
        }
    }
}
